using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SomeRandomGame.Interfaces;

namespace SomeRandomGame.Particles.Engines
{
    public class ShipMotorParticleEngine : IParticleEngine
    {
        public Vector2 EmitterLocation { get; set; }

        private readonly Random _random;
        private readonly List<ShipMotorParticle> _particles;
        private readonly Texture2D _texture;
        private readonly Color[] _possibleParticleColors;

        public ShipMotorParticleEngine(Texture2D texture, Vector2 location)
        {
            EmitterLocation = location;
            _texture = texture;
            _particles = new List<ShipMotorParticle>();
            _possibleParticleColors = GetPossibleParticleColors();
            _random = new Random();
        }

        private Color[] GetPossibleParticleColors()
        {
            Color[] result = new Color[4];
            result[0] = Color.Brown;
            result[1] = Color.RosyBrown;
            result[2] = Color.SaddleBrown;
            result[3] = Color.SandyBrown;
            return result;
        }

        private ShipMotorParticle GenerateNewParticle()
        {
            Vector2 position = EmitterLocation;
            Vector2 velocity = new Vector2(
                                    -0.1f,
                                    1f * (float)(_random.NextDouble() * 2 - 1));
            const float angle = 0;
            float angularVelocity = 0.1f * (float)(_random.NextDouble() * 2 - 1);
            Color color = _possibleParticleColors[_random.Next(0, 3)];
            float size = (float)_random.NextDouble();
            int ttl = 20 + _random.Next(40);

            return new ShipMotorParticle(_texture, position, velocity, angle, angularVelocity, color, size, ttl);
        }

        public void Initialize(IGameManager gameManager)
        {
        }

        public void Update(IGameManager gameManager)
        {
            const int total = 20;

            for (int i = 0; i < total; i++)
            {
                _particles.Add(GenerateNewParticle());
            }

            for (int particle = 0; particle < _particles.Count; particle++)
            {
                _particles[particle].Update(gameManager);
                if (_particles[particle].Ttl <= 0)
                {
                    _particles.RemoveAt(particle);
                    particle--;
                }
            }
        }

        public void Draw(SpriteBatch spriteBatch, IGameManager gameManager, GameTime gameTime)
        {
            spriteBatch.Begin();
            foreach (ShipMotorParticle t in _particles)
            {
                t.Draw(spriteBatch, gameManager, gameTime);
            }
            spriteBatch.End();
        }
    }
}
